<template>
    <div class="chat-container">
      <div class="chat-box">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <span v-if="message.sender === 'user'" class="user-message">You: </span>
          <span v-else class="bot-message">Bot: </span>
          {{ message.text }}
        </div>
      </div>
      <div class="input-container">
        <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type a message..." />
        <button @click="sendMessage">Send</button>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, onMounted, onBeforeUnmount } from 'vue';
  import io from 'socket.io-client';
  
  export default {
    setup() {
      const messages = ref([]);
      const newMessage = ref('');
      let socket;
  
      const sendMessage = () => {
        if (newMessage.value.trim() !== '') {
          messages.value.push({ text: newMessage.value, sender: 'user' });
          socket.send(newMessage.value);
          newMessage.value = '';
        }
      };
  
      onMounted(() => {
        // Replace 'http://localhost:3000' with your WebSocket server URL
        socket = new WebSocket("ws://localhost:8000/ws");

        // Listen for messages from the server
        socket.onmessage = function(event) {
                messages.value.push({ text: event.data, sender: 'bot' });
            };
      });
  
      onBeforeUnmount(() => {
        if (socket) {
          socket.disconnect();
        }
      });
  
      return { messages, newMessage, sendMessage };
    },
  };
  </script>
  
  <style scoped>
  .chat-container {
    display: flex;
    flex-direction: column;
    max-width: 400px;
    margin: auto;
    padding: 20px;
  }
  
  .chat-box {
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px;
    max-height: 300px;
    overflow-y: auto;
  }
  
  .message {
    margin-bottom: 10px;
    padding: 8px;
    border-radius: 4px;
  }
  
  .user-message {
    font-weight: bold;
    color: blue;
  }
  
  .bot-message {
    font-weight: bold;
    color: green;
  }
  
  .input-container {
    margin-top: 10px;
    display: flex;
  }
  
  input {
    flex: 1;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
  
  button {
    margin-left: 8px;
    padding: 8px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }
  </style>
  